package org.example.config;

import cn.hutool.core.util.StrUtil;
import org.example.dto.ColumnDto;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

public class MysqlExecute {
    private Connection conn;
    private Statement stmt;

    public MysqlExecute(Properties properties) throws Exception {
        String url = properties.getProperty("mysql.datasource.url");
        String username = properties.getProperty("mysql.datasource.username");
        String password = properties.getProperty("mysql.datasource.password");
        String driver = properties.getProperty("mysql.datasource.driver-class-name");
        Class.forName(driver);
        conn = DriverManager.getConnection(url, username, password);
        stmt = conn.createStatement();
    }

    public List<String> getTables() throws Exception {
        String sql = "SHOW TABLES";
        ResultSet rs = stmt.executeQuery(sql);
        List<String> tables = new ArrayList<>();
        while (rs.next()) {
            tables.add(rs.getString(1));
        }
        return tables;
    }

    public List<ColumnDto> getFields(String table) {
        List<ColumnDto> tables = null;
        try {
            String sql = StrUtil.format("SHOW FULL COLUMNS FROM {}", table);
            ResultSet rs = stmt.executeQuery(sql);
            tables = new ArrayList<>();
            while (rs.next()) {
                ColumnDto columnDto = new ColumnDto();
                columnDto.setField(rs.getString(1));
                columnDto.setType(rs.getString(2));
                columnDto.setRemark(rs.getString(9));
                tables.add(columnDto);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return tables;
    }

    public void close() throws Exception {
        stmt.close();
        conn.close();
    }
}
